import requests
from urllib import request


def download_music(music_id, music_name, path):
    url = f'http://music.163.com/song/media/outer/url?id={music_id}'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
                      '(KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36 Edg/88.0.705.56',
        'Host': 'music.163.com',
        'Referer': 'https://music.163.com/'
    }

    req = requests.get(url, headers=headers, allow_redirects=False)
    song_url = req.headers['Location']
    try:
        # path在主函数中输入
        print('path:', path)
        io_addr = path.replace('\\', '\\\\')
        request.urlretrieve(song_url, io_addr + '\\music' + f"\\{music_name}.mp3")
        print('download finish')
    except Exception as e:
        print('error:\n', e)
